import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { UserEntity } from '@/src/user/entities/user.entity'
import { RedisService } from '../redis/redis.service'

@Injectable()
export class TokenService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService
  ) { }

  // 生成token
  async generateToken(user: UserEntity) {
    const payload = {
      id: user.id,
      account: user.account || user.phone,
      role: user.role
    }
    const access_token = this.jwtService.sign(payload, {
      expiresIn: '6h',
    })
    await this.redisService.set(`token_${user.id}`, access_token, 3600 * 6)

    return {
      token: access_token,
      type: 'Bearer'
    }
  }
}